package verifycode

import (
	"context"
	"git.mycaigou.com/gfyx/common/cache"
	"git.myscrm.cn/golang/common/ykenv"
	"git.myscrm.cn/golang/stark/v4"
	"time"
)

var (
	expire_time       = 10 // 默认 10 分钟
	debug_expire_time = 10080
)

// RedisStore 实现 verifycode.Store interface
type RedisStore struct {
	RedisClient *cache.TRedis
	KeyPrefix   string
	ctx         context.Context
}

// Set 实现 verifycode.Store interface 的 Set 方法
func (s *RedisStore) Set(key string, value string) bool {
	ExpireTime := time.Minute * time.Duration(expire_time)
	// 本地环境方便调试
	if ykenv.IsDevMode() {
		ExpireTime = time.Minute * time.Duration(debug_expire_time)
	}
	if _, err := s.RedisClient.Set(s.ctx, s.KeyPrefix+key, value, true, int(ExpireTime)); err != nil {
		stark.Logger.Errorf(s.ctx, "set verify code failed, key:%s, err:%+v", key, err)
		return false
	}
	return true
}

// Get 实现 verifycode.Store interface 的 Get 方法
func (s *RedisStore) Get(key string, clear bool) (value string) {
	key = s.KeyPrefix + key
	val, _ := s.RedisClient.Get(s.ctx, key)
	if clear {
		s.RedisClient.Del(s.ctx, key)
	}
	return val
}

// Verify 实现 verifycode.Store interface 的 Verify 方法
func (s *RedisStore) Verify(key, answer string, clear bool) bool {
	v := s.Get(key, clear)
	return v == answer
}
